package org.shezhua.android.i18n;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.eclipse.ui.console.MessageConsoleStream;
import org.shezhua.android.i18n.model.ResString;
import org.shezhua.android.i18n.model.ResValues;

public class AndroidResStringReader {
	private Map<String, ResValues> values = new HashMap<String, ResValues>();
	private MessageConsoleStream consoleStream;
	
	public static void main(String[] args) throws Exception {
		new AndroidResStringReader().scan("C:\\Users\\Lenovo\\mm");
	}
	
	public AndroidResStringReader() {
	}
	
	public AndroidResStringReader(MessageConsoleStream consoleStream) {
		this.consoleStream = consoleStream;
	}

	public void clear() {
		values.clear();
	}
	
	public Map<String, ResValues> getResult() {
		return values;
	}
	
	@SuppressWarnings("unchecked")
	public Map<String, ResValues> scan(String path) {
		consoleStream.println("Begin scan: " + path);
		
		List<File> files = findXmlFile(new File(path));
		
		SAXReader reader = new SAXReader();
		reader.setEncoding("UTF-8");
		reader.setValidation(false);
		
		for (File file : files) {
			Document doc = null;
			try {
		        doc = reader.read(file);
		        
				Element root = doc.getRootElement();
				if(!"resources".equals(root.getName())) {
					continue;
				}
				Iterator it = root.elementIterator();
				while(it.hasNext()) {
					Element e = (Element) it.next();
					if("string".equals(e.getName())) {
						String key = e.attributeValue("name");
						
						ResString rs = new ResString();
						rs.setFile(file);
						rs.setKey(key);
						rs.setValue(e.getText());
						
						ResValues v = null;
						if(values.containsKey(key)) {
							v = values.get(key);
							v.put(rs.getFileName(), rs);
						} else {
							v = new ResValues(key);
							v.put(rs.getFileName(), rs);
							values.put(key, v);
						}
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				doc = null;
			}
		}
		return values;
	}

	List<File> findXmlFile(File path) {
		if(path.exists() && path.isDirectory()) {
			List<File> files = new ArrayList<File>();
			File[] listFiles = path.listFiles();
			for (File file : listFiles) {
				if(file.isDirectory()) {
					files.addAll(findXmlFile(file));
				} else {
					String parent = file.getParentFile().getName();
					String name = file.getName();
					if(parent.startsWith("values") && name.toLowerCase().endsWith(".xml")) {
						this.consoleStream.println("  Found xml file: " + file.getAbsolutePath());
						files.add(file);
					}
				}
			}
			return files;
		}
		return Collections.emptyList();
	}
}
